{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ff9ab1cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch # 导入 torch\n",
    "import torch.nn.functional as F # 导入 nn.functional\n",
    "# 1. 创建两个张量 x1 和 x2\n",
    "x1 = torch.randn(2, 3, 4) # 形状 (batch_size, seq_len1, feature_dim)\n",
    "x2 = torch.randn(2, 5, 4) # 形状 (batch_size, seq_len2, feature_dim)\n",
    "# 2. 计算张量点积，得到原始权重\n",
    "raw_weights = torch.bmm(x1, x2.transpose(1, 2)) # 形状 (batch_size, seq_len1, seq_len2)\n",
    "# 3. 将原始权重除以缩放因子\n",
    "scaling_factor = x1.size(-1) ** 0.5\n",
    "scaled_weights = raw_weights  / scaling_factor # 形状 (batch_size, seq_len1, seq_len2)\n",
    "# 4. 对原始权重进行归一化\n",
    "attn_weights  =  F.softmax(raw_weights, dim=2) #  形 状 (batch_size,  seq_len1,  seq_len2)\n",
    "# 5. 使用注意力权重对 x2 加权求和\n",
    "attn_output = torch.bmm(attn_weights, x2)  # 形状 (batch_size, seq_len1, feature_dim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9973de74",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[-0.9441,  0.0333, -0.9783,  0.5203],\n",
       "         [-0.7254,  0.0468, -0.4820,  0.2385],\n",
       "         [-0.2992, -0.0417, -0.0295, -0.1619]],\n",
       "\n",
       "        [[-0.2492,  0.8127,  0.8505,  1.1146],\n",
       "         [ 0.2276, -1.1925, -0.4009,  0.4734],\n",
       "         [-0.1156,  0.6940,  0.1888,  0.9142]]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "attn_output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97ab79b9",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
